/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\CustomerManage\Customer\List\DistributorDataTable\DistributorDataTable.tsx
 * @Date: 2023-05-26 18:50:58
 * @LastEditTime: 2023-05-31 15:43:46
 * @LastEditors: Setsuna
 */
import React from 'react'
import { http, columnRenders, UdDrawer, UdFilter, UdTable, IUdColumn } from '@/lib'
import _ from 'lodash'
import { Select, Spin, TreeSelect } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import customerApis from '@/apis/CustomerManage'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import apis from '@/apis'
import ProductsandSuppliersTable from '../TerminalDataTable/ProductsandSuppliersTable'
import CustomerDetailsTable from '../TerminalDataTable/CustomerDetailsTable'
import SelectLowerTable from './SelectLowerTable'

const Option = Select.Option
const { TreeNode } = TreeSelect
export default class DistributorDataTable extends React.PureComponent<any, any> {
  private filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList = udMainStore.brandList
  private columns: IUdColumn<any>[] = [
    { title: '序号', dataIndex: 'id', key: 'id', width: 50, render: (text, record, index) => index + 1 },
    { title: '客户编码', dataIndex: 'acctCode', width: '100px' },
    { title: '客户名称', dataIndex: 'acctName', width: '200px' },
    // { title: '客户类型', dataIndex: 'agentType', width: '100px', render: (text, reoled, index) => '分销商' },
    { title: '品牌公司', dataIndex: 'salesmanBrandCom', width: '200px' },
    { title: '联系人电话', dataIndex: 'salemanMobilePhone', width: '100px' },
    { title: '手机号', dataIndex: 'mobilePhone', width: '100px' },
    { title: '经营税号', dataIndex: 'creditNo', width: '100px' },
    { title: '省', dataIndex: 'province', width: '100px' },
    { title: '市', dataIndex: 'city', width: '100px' },
    { title: '区', dataIndex: 'district', width: '100px' },
    { title: '联系地址', dataIndex: 'address', width: '200px' },
    {
      title: '状态',
      dataIndex: 'acctStatus',
      key: 'acctStatus',
      width: 80,
      render: (text, record, index) => (text === 'Y' ? '启用' : '禁用'),
    },
    {
      title: '操作',
      dataIndex: 'operate',
      width: '280px',
      fixed: 'right',
      render: columnRenders.operate(
        [
          { title: '查看下级客户', action: (text, record) => this.handSelectLowerLevelData(record) },
          {
            title: '所属产品及供应商',
            action: (text, record) => this.handGetProductsandSuppliersData(record),
          },
          {
            title: '客户明细',
            action: (text, record) => this.handGetCustomerDetailsData(record),
          },
        ],
        4
      ),
    },
  ]
  state = {
    loading: false,
    uploading: false,
    downloading: false,
    title: '客户管理',
    page: 1,
    size: 10,
    total: 0,
    searchValues: {
      mdmCompanyCode: this.brandList[0].value,
      acctType: 'Distributor',
    },
    dataSource: [],
    conditions: [
      {
        label: '品牌公司',
        id: 'mdmCompanyCode',
        initialValue: this.brandList[0].value,
        render: (
          <UdSelect
            showSearch
            allowClear={true}
            options={this.brandList}
            onChange={value => {
              this.changeBrandCode(value)
            }}
          />
        ),
      },
      {
        label: '所属组织',
        id: 'orgCode',
        render: () => (
          <TreeSelect showSearch treeNodeFilterProp="title">
            {this.mapTree(this.state.treeDataList)}
          </TreeSelect>
        ),
      },
      { id: 'acctCode', label: '客户编码' },
      { id: 'acctName', label: '客户名称' },
      { id: 'mobilePhone', label: '手机号' },
      {
        id: 'acctStatus',
        label: '状态',
        render: (
          <Select>
            <Option value={'Y'}>启用</Option>
            <Option value={'N'}>禁用</Option>
          </Select>
        ),
      },
    ],
    brandCompanies: [],
    treeDataList: [],
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }
  private changeBrandCode = (value: any) => {
    this.filterForm.setFieldsValue({ prodBarcode: undefined, belongAreaCode: undefined }, () => {
      this.setState({ treeDataList: [] }, () => {
        Promise.allSettled([this.getAreaList(value)]).then((res: any) => {
          this.setState({
            treeDataList: res[0]?.value || [],
          })
        })
      })
    })
  }
  private getAreaList = (value: any) => {
    if (Object.is(value, undefined)) return []
    return http
      .get(apis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  private handSelectLowerLevelData = (record): void => {
    UdDrawer.open({
      title: '下级客户信息',
      cancelText: null,
      width: '80%',
      content: (
        <SelectLowerTable
          brandList={this.brandList}
          brandCode={record.mdmCompanyCode}
          acctName={record.acctName}
          acctCode={record.acctCode}
        />
      ),
    })
  }

  private handGetProductsandSuppliersData = (record: Record<string, any>): void => {
    UdDrawer.open({
      title: '所属产品及供应商',
      cancelText: null,
      width: '80%',
      content: <ProductsandSuppliersTable record={record} />,
    })
  }
  private handGetCustomerDetailsData = (record: Record<string, any>): void => {
    UdDrawer.open({
      title: '客户明细',
      cancelText: null,
      width: '80%',
      content: <CustomerDetailsTable record={record} />,
    })
  }

  public componentDidMount() {
    this.getRecordTableData()
  }
  render() {
    let { loading, uploading, downloading, conditions, dataSource, page, size, total } = this.state
    return (
      <Spin spinning={uploading || downloading} tip={uploading ? '上传中，请稍后...' : '请求中，请稍后...'}>
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdTable
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={dataSource}
          onChange={this.handleChangePage}
          scroll={{ x: true }}
          pagination={{
            current: page,
            pageSize: size,
            total: total,
            showQuickJumper: false,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </Spin>
    )
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private handleSearch = (values: object) => {
    this.setState({ searchValues: { ...values, acctType: 'Distributor' }, dataSource: [], page: 1, total: 0 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState(
      { searchValues: { ...form.getFieldsValue(), acctType: 'Distributor' }, dataSource: [], page: 1, total: 0 },
      () => {
        this.getRecordTableData()
      }
    )
  }

  private getRecordTableData = async () => {
    this.setState({ loading: true })
    let { page, size, searchValues } = this.state
    http
      .post(customerApis.getCustomerPage, {
        page,
        size,
        conditions: { ...searchValues },
      })
      .then(res => {
        const dataSource = res.data?.content
        this.setState({
          dataSource,
          total: res.data.totalElements,
        })
      })
      .finally(() => {
        this.setState({
          loading: false,
        })
      })
  }
}
